package com.example.active.trans;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.Scanner;

public class Sender implements Runnable{
    public String url;
    public String topicName;

    public String pid;

    public Sender(String url, String topicName, String pid) {
        this.url = url;
        this.topicName = topicName;
        this.pid = pid;
    }

    @Override
    public void run() {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        try {
            Connection connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(topicName);
            MessageProducer producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            Scanner in = new Scanner(System.in);
            while (in.hasNext()) {
                TextMessage message = session.createTextMessage(String.format("%s : %s", pid, in.nextLine()));
                producer.send(message);
                session.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
